﻿using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Baby.Shop.Application.Common.Impl
{
    public class RedisCacheHelper
    {
        private readonly IDatabase _db;

        public RedisCacheHelper(ConnectionMultiplexer _redis)
        {
            _db = _redis.GetDatabase();
        }

        public T Get<T>(string key)
        {
            var serialized = _db.StringGet(key);
            if (serialized.IsNullOrEmpty)
            {
                return default(T);
            }
            return Deserialize<T>(serialized);
        }

        public void Set<T>(string key, T value)
        {
            var serialized = Serialize(value);
            _db.StringSet(key, serialized);
        }

        public void Remove(string key)
        {
            _db.KeyDelete(key);
        }

        private string Serialize(object value)
        {
            return JsonConvert.SerializeObject(value);
        }

        private T Deserialize<T>(string serialized)
        {
            return JsonConvert.DeserializeObject<T>(serialized);
        }

        public void Dispose()
        {
            //_db.f();
        }
    }
}
